问题描述(难度简单-169)
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
1 | Input: [3,2,3] |
Example 2:
1 | Input: [2,2,1,1,1,2,2] |
方法一:排序
直接排序,取出中间的索引值。因为数量大于一半,所以中间的值肯定是大多数的值。时间复杂度O(nlogn),空间复杂度O(1)。
1 | public class Solution { |
方法二:using hash
一遍扫描,用HashMap记录出现的次数,中间记录出现最多的key。时间复杂度O(n),空间复杂度O(n)。
1 | package P169; |
方法三:一遍遍历
利用数组中某一个数一定会出现一半以上这个特点,只需要一遍遍历就可以完成。时间复杂度O(n),空间复杂度O(1)。
1 | public class Solution { |
总结
一遍遍历的方法比较巧妙。利用了同一个数字出现的次数大于一半以上。